this.WbstChart = this.WbstChart || {};
(function(){
	var mapChart = function(stage, renderer)
	{
		this._creationCompleteFlag = false;

		if (stage == null)
		{
			 stage = new PIXI.Stage();
		}
		this._stage = stage;
		if (renderer == null)
		{
			renderer = PIXI.autoDetectRenderer(document.innerWidth, document.innerHeight, {transparent: true});
			document.body.appendChild(renderer.view);
		}
		this._renderer = renderer;

		// 地图区块容器。
		this._itemBase = new PIXI.DisplayObjectContainer();
		this._stage.addChild(this._itemBase);

		// 地图投影器。
		this._projector = new WbstChart.DefaultProjector();
		// 地图样式协调器。
		this._styleCoordinator = new WbstChart.DefaultStyleCoordinator();

		// 缓存地图Id和地图轮廓等信息。
		this._mapKIdVInfo = {};
		var id = 'countries';
		var current = this;
		this._callBack = function(info)
		{
			current.webstudioMapInfo(info);
		}
		this.loadMapData(id);
		// if (id == 'countries') this._projector._offsetX = -150;
		
		this.EventDispatcher = $({});



		var current = this;
		this._currentState = 'firstLevel';

		this._firstLevelBtn = $('#firstLevelBtn');
		this._secondLevelBtn = $('#secondLevelBtn');
		this._thirdLevelBtn = $('#thirdLevelBtn');
		if (this._firstLevelBtn)
		{
			this._firstLevelBtn.click(function() {
				current._currentState = 'firstLevel';
				for (var i = 0; i < current._currentItem._children.length; i++)
				{
					current._itemBase.removeChild(current._currentItem._children[i]._graphics);
				}
				current._currentItem = null;
				if (current._preLevelItem)
				{
					for (var i = 0; i < current._preLevelItem._children.length; i++)
					{
						current._itemBase.removeChild(current._preLevelItem._children[i]._graphics);
					}
					current._preLevelItem = null;
				}
				current._firstLevelBtn.css({
					display: 'none'
				});
				current._firstLevelBtn.next().css({
					display: 'none'
				});
				current._secondLevelBtn.css({
					display: 'none'
				});
				current._secondLevelBtn.next().css({
					display: 'none'
				});
				current._thirdLevelBtn.css({
					display: 'none'
				});

				current.EventDispatcher.trigger('removeElements');
				TweenMax.to(current._boundingBox, 0.6, {
					minX: current._webstudioMapInfo.polygon.boundingBox.minX,
					minY: current._webstudioMapInfo.polygon.boundingBox.minY,
					maxX: current._webstudioMapInfo.polygon.boundingBox.maxX,
					maxY: current._webstudioMapInfo.polygon.boundingBox.maxY,
					onUpdate: function() {
						current.resize();
					},
					onComplete: function() {
						current.EventDispatcher.trigger('addElements');
					}
				});
			});
		}
		if (this._secondLevelBtn)
		{
			this._secondLevelBtn.click(function() {
				if (current._currentState == 'secondLevel') return;
				current._currentState = 'secondLevel';
				for (var i = 0; i < current._currentItem._children.length; i++)
				{
					current._itemBase.removeChild(current._currentItem._children[i]._graphics);
				}
				current._currentItem = current._preLevelItem;
				current._preLevelItem = null;
				current._secondLevelBtn.next().css({
					display: 'none'
				});
				current._thirdLevelBtn.css({
					display: 'none'
				});

				current.EventDispatcher.trigger('removeElements');
				TweenMax.to(current._boundingBox, 0.6, {
					minX: current._currentItem._info.polygon.boundingBox.minX,
					minY: current._currentItem._info.polygon.boundingBox.minY,
					maxX: current._currentItem._info.polygon.boundingBox.maxX,
					maxY: current._currentItem._info.polygon.boundingBox.maxY,
					onUpdate: function() {
						current.resize();
					},
					onComplete: function() {
						current.EventDispatcher.trigger('addElements');
					}
				});
			});
		}
	}

	var p = mapChart.prototype;

	p.webstudioMapInfo = function(value)
	{
		if (this._webstudioMapInfo == value) return;
		this._webstudioMapInfo = value;

		this.creationContent();
	}
	p.styleCoordinator = function(value)
	{
		if (value) this._styleCoordinator = value;
	}

	p.creationContent = function()
	{
		if (this._webstudioMapInfo == null) return;

		// for (var i = this._itemBase.numChildren - 1; i >= 0; i++)
		// {
		// 	var item = this._itemBase.getChildAt(i);
		// 	this.removeMapItem(item);
		// }

		// 缓存地图Id和地图区块信息。
		this._mapKIdVItem = {};
		// 当前呈现的地图边界。
		this._boundingBox = {};

		for (var i = 0; i < this._webstudioMapInfo.children.length; i++)
		{
			this.addMapItem(this._webstudioMapInfo.children[i]);
		}

		this._boundingBox.minX = this._webstudioMapInfo.polygon.boundingBox.minX;
		this._boundingBox.minY = this._webstudioMapInfo.polygon.boundingBox.minY;
		this._boundingBox.maxX = this._webstudioMapInfo.polygon.boundingBox.maxX;
		this._boundingBox.maxY = this._webstudioMapInfo.polygon.boundingBox.maxY;

		// this._projector._scale = 1;
		// var p0 = this._projector.lngLatToXY(this._webstudioMapInfo.polygon.boundingBox.minX, this._webstudioMapInfo.polygon.boundingBox.minY);
		// var p1 = this._projector.lngLatToXY(this._webstudioMapInfo.polygon.boundingBox.maxX + (this._webstudioMapInfo.polygon.boundingBox.maxX - this._webstudioMapInfo.polygon.boundingBox.minX), this._webstudioMapInfo.polygon.boundingBox.maxY);
		// this._boundingBox.minX = Math.min(p0.x, p1.x);
		// this._boundingBox.minY = -Math.max(p0.y, p1.y);
		// this._boundingBox.maxX = Math.max(p0.x, p1.x);
		// this._boundingBox.maxY = -Math.min(p0.y, p1.y);


		this._creationCompleteFlag = true;

		this.resize();
	}

	p.excludeMapItem = function(level, info)
	{
		// if (info.id == 'ATA' || info.id == 'GRL') return true;
		if (info.id == 'GRL') return true;
		return false;
	}

	/**
	 * 创建地图区块。
	 */
	p.addMapItem = function(info, parentItem)
	{
		var level = parentItem == null ? 0 : parentItem._level + 1;

		if (this.excludeMapItem(level, info)) return;

		var item = new WbstChart.MapChartItem();
		item._id = info.id;
		item._zh_name = info.name == 'China' ? '中国' : info.name;
		item._level = level;
		item.info(info);
		item.projector(this._projector);
		item.styleCoordinator(this._styleCoordinator);
		this._mapKIdVItem[item._id] = item;

		if (parentItem) parentItem._children.push(item);

		this._itemBase.addChild(item._graphics);

		var current = this;
		item._graphics.interactive = true;
		item._graphics.mouseover = function(data)
		{
			item.redraw('mouseover');
			current._renderer.render(current._stage);

			// current.EventDispatcher.trigger('MapChartItemMouseOver', item);
		};
		item._graphics.mouseout = function(data)
		{
			item.redraw('mouseout');
			current._renderer.render(current._stage);

			// current.EventDispatcher.trigger('MapChartItemMouseOut', item);
		};
		item._graphics.click = function(data)
		{
			current.expandItems([item._id]);

			current.EventDispatcher.trigger('MapChartItemClick', item);
		};
	}
	// p.removeMapItem = function(item)
	// {
	// 	item.info(null);
	// 	item._children = [];
	// 	delete this._mapKIdVItem[item._id];
	// }

	/**
	 * 下钻到指定的地图区块，支持同时下钻多个区块。
	 * @param itemIds 地图区块Id数组
	 */
	p.expandItems = function(itemIds)
	{
		this._itemsOfExistChildren = [];
		this._itemsOfNeedLoadChildren = [];
		for (var i = 0; i < itemIds.length; i++)
		{
			var item = this._mapKIdVItem[itemIds[i]];

			// 当前钻取的对象，目前只针对钻取一个区块的情况
			if (this._currentState == 'firstLevel')
			{
				this._currentItem = item;

				this._currentState = 'secondLevel';
				this._secondLevelBtn.text(item._zh_name);
				this._firstLevelBtn.css({
					display: 'inline'
				});
				this._firstLevelBtn.next().css({
					display: 'inline'
				});
				this._secondLevelBtn.css({
					display: 'inline'
				});
			}
			else if (this._currentState == 'secondLevel')
			{
				this._preLevelItem = this._currentItem;
				this._currentItem = item;

				this._currentState = 'thirdLevel';
				this._thirdLevelBtn.text(item._zh_name);
				this._secondLevelBtn.next().css({
					display: 'inline'
				});
				this._thirdLevelBtn.css({
					display: 'inline'
				});
			}

			// 子区块已经加载过，只需将子区块重新添加到stage。
			if (item._children.length > 0)
			{
				for (var j = 0; j < item._children.length; j++)
				{
					this._itemBase.addChild(item._children[j]._graphics);
				}
				this._itemsOfExistChildren.push(item);
				// expand();
			}
			// 子区块还未加载，则需要加载子区块。
			else
			{
				this._itemsOfNeedLoadChildren.push(item);
			}
		}

		var numNeedLoad = this._itemsOfNeedLoadChildren.length;
		var numLoaded = 0;
		this._callBack = function(info)
		{
			numLoaded++;
			for (var i = 0; i < info.children.length; i++)
			{
				this.addMapItem(info.children[i], this._mapKIdVItem[info.id]);
			}
			if (numLoaded == numNeedLoad) expand();
		};
		for (var i = 0; i < this._itemsOfNeedLoadChildren.length; i++)
		{
			this.loadMapData(this._itemsOfNeedLoadChildren[i]._id);
		}

		var current = this;
		var expand = function()
		{
			// 找到下钻区块的边界。
			var minX = Number.MAX_VALUE, minY = Number.MAX_VALUE, maxX = Number.MIN_VALUE, maxY = Number.MIN_VALUE;
			for (var i = 0; i < current._itemsOfExistChildren.length; i++)
			{
				var item = current._itemsOfExistChildren[i];
				minX = Math.min(minX, item._info.polygon.boundingBox.minX);
				minY = Math.min(minY, item._info.polygon.boundingBox.minY);
				maxX = Math.max(maxX, item._info.polygon.boundingBox.maxX);
				maxY = Math.max(maxY, item._info.polygon.boundingBox.maxY);
			}
			for (var i = 0; i < current._itemsOfNeedLoadChildren.length; i++)
			{
				var item = current._itemsOfNeedLoadChildren[i];
				minX = Math.min(minX, item._info.polygon.boundingBox.minX);
				minY = Math.min(minY, item._info.polygon.boundingBox.minY);
				maxX = Math.max(maxX, item._info.polygon.boundingBox.maxX);
				maxY = Math.max(maxY, item._info.polygon.boundingBox.maxY);
			}

			current.EventDispatcher.trigger('removeElements');
			TweenMax.to(current._boundingBox, 0.6, {
				minX: minX,
				minY: minY,
				maxX: maxX,
				maxY: maxY,
				onUpdate: function()
				{
					current.resize();
				},
				onComplete: function()
				{
					current.EventDispatcher.trigger('addElements');
				}
			});
		}
	}
	
	// /**
	//  * 下钻到指定的地图区块。
	//  */
	// p.expandItem = function(item)
	// {
	// 	if (item._children.length > 0)
	// 	{
	// 		for (var i = 0; i < item._children.length; i++)
	// 		{
	// 			this._itemBase.addChild(item._children[i]);
	// 		}
	// 		console.log('直接放大。')
	// 		expand();
	// 	}
	// 	else
	// 	{
	// 		this._callBack = function(info)
	// 		{
	// 			for (var i = 0; i < info.children.length; i++)
	// 			{
	// 				this.addMapItem(info.children[i], item);
	// 			}
	// 			console.log('先装载数据，再执行放大。')
	// 			expand();
	// 		};
	// 		this.loadMapData(item._id);
	// 	}

	// 	var current = this;
	// 	var expand = function()
	// 	{
	// 		var targetBoundingBox = item._info.polygon.boundingBox;
	// 		TweenMax.to(current._boundingBox, 0.6, {
	// 			minX: targetBoundingBox.minX,
	// 			minY: targetBoundingBox.minY,
	// 			maxX: targetBoundingBox.maxX,
	// 			maxY: targetBoundingBox.maxY,
	// 			onUpdate: function()
	// 			{
	// 				current.resize();
	// 			}
	// 		});
	// 	}
	// }

	p.resize = function(size)
	{
		if (size)
		{
			// if (this._width == size.width && this._height == size.height) return;
			this._width = size.width;
			this._height = size.height;
		}
		// renderer resize。
		this._renderer.resize(this._width, this._height);

		if (!this._creationCompleteFlag) return;

		var boxWidth = this._boundingBox.maxX - this._boundingBox.minX;
		var boxHeight = this._boundingBox.maxY - this._boundingBox.minY;
		var scaleW = this._width / boxWidth;
		var scaleH = this._height / boxHeight;
		this._scale = Math.min(scaleW, scaleH);
		this._scale /= 1.3;
		this._projector._scale = this._scale;

		for (var i = 0; i < this._itemBase.children.length; i++)
		{
			var item = this._itemBase.getChildAt(i);
			if (item.hasOwnProperty('_parentClass'))
			{
				item = item._parentClass;


				// item是否正常显示，钻取时，只有钻取对象的子级正常显示
				// 其他全部将透明度设置为0.1
				if (this._currentItem)
				{
					if (item == this._currentItem
						|| item._children.indexOf(this._currentItem) != -1
						|| this._currentItem._children.indexOf(item) == -1
					)
					{
						item.itemNormalShow = false;
					}
					else
					{
						item.itemNormalShow = true;
					}
				}
				else
				{
					item.itemNormalShow = true;
				}


				item.redraw('mouseout');
			}
		}

		// center it
		var center = this._projector.lngLatToXY(this._boundingBox.minX + boxWidth / 2, this._boundingBox.minY + boxHeight / 2);
		this._itemBase.x = boxWidth * this._scale / 2 + (this._width - boxWidth * this._scale) / 2 - center.x;// + this._projector._offsetX * this._scale;
		this._itemBase.y = boxHeight * this._scale / 2 + (this._height - boxHeight * this._scale) / 2 - center.y;

		this._renderer.render(this._stage);
	}

	/**
	 * 获取经纬度在本地图的XY坐标。
	 */
	p.getPoint = function(lng, lat)
	{
		var p = this._projector.lngLatToXY(lng, lat);
		p.x += this._itemBase.x;
		p.y += this._itemBase.y;
		return p;
	}

	/**
	 * 加载地图数据。
	 */
	p.loadMapData = function(id)
	{
		var parentInfo = this._mapKIdVInfo[id];
		if (parentInfo == null)
		{
			parentInfo = {id: id, name: '', polygon: {parts: [], boundingBox: {}}};
			this._mapKIdVInfo[id] = parentInfo;
		}

		var current = this;
		// 加载、解析地图数据。
		$.get('mapData/' + id + '.geo.json', function(mapData)
		{
			parentInfo.children = [];

			var numPoint = 0;

			var minX = Number.MAX_VALUE, minY = Number.MAX_VALUE, maxX = Number.MIN_VALUE, maxY = Number.MIN_VALUE;
			for (var i = 0; i < mapData.features.length; i++)
			{
				var data = mapData.features[i];

				var polygon = {parts: [], boundingBox: {}};
				var childInfo = {id: data.id, name: data.properties.name, polygon: polygon};
				var arr1 = data.geometry.coordinates;
				var type = data.geometry.type;
				for (var j = 0; j < arr1.length; j++)
				{
					var pointXs = [];
					var pointYs = [];
					var part = {pointXs: pointXs, pointYs: pointYs};
					var arr2 = arr1[j];
					if (type == 'MultiPolygon') arr2 = arr2[0];
					for (var k = 0; k < arr2.length; k++)
					{
						var arr3 = arr2[k];

						var x = arr3[0];
						var y = arr3[1];
						if (isNaN(x) || isNaN(y)) continue;
						minX = Math.min(x, minX);
						minY = Math.min(y, minY);
						maxX = Math.max(x, maxX);
						maxY = Math.max(y, maxY);

						pointXs.push(arr3[0]);
						pointYs.push(arr3[1]);

						numPoint++;
					}
					polygon.parts.push(part);
				}

				parentInfo.children.push(childInfo);

				current._mapKIdVInfo[childInfo.id] = childInfo;
			}

			parentInfo.polygon.boundingBox.minX = minX;
			parentInfo.polygon.boundingBox.minY = minY;
			parentInfo.polygon.boundingBox.maxX = maxX;
			parentInfo.polygon.boundingBox.maxY = maxY;

			if (current._callBack) current._callBack(parentInfo);
		});
	}

	WbstChart.MapChart = mapChart;
})();

/**
 * 地图的区块区块。
 */
(function(){
	var mapChartItem = function()
	{
		this._graphics = new PIXI.Graphics();
		this._graphics._graphicsName = 'mapItem';
		this._graphics._parentClass = this;

		this._children = [];
	}

	var p = mapChartItem.prototype;

	// 地图区块信息。
	p.info = function(value)
	{
		this._info = value;
	}

	// 地图投影器。
	p.projector = function(value)
	{
		this._projector = value;
	}
	// 地图样式协调器。
	p.styleCoordinator = function(value)
	{
		this._styleCoordinator = value;
	}

	p.redraw = function(type)
	{
		this._graphics.clear();

		var polygon = this._info.polygon;
		for (var i = 0; i < polygon.parts.length; i++)
		{
			if (this.itemNormalShow)
			{
				this._styleCoordinator.styleShape(this._graphics, this._level, this._info, type);
			}
			else
			{
				this._graphics.beginFill(0xffffff).lineStyle(1, 0x212232);
				this._graphics.fillAlpha = 0.05;
			}


			var part = polygon.parts[i];
			for (var j = 0; j < part.pointXs.length; j++)
			{
				var p = this._projector.lngLatToXY(part.pointXs[j], part.pointYs[j]);
				if (j == 0) this._graphics.moveTo(p.x + 50, p.y);
				else this._graphics.lineTo(p.x + 50, p.y);
			}
			this._graphics.endFill();
		}
	}

	WbstChart.MapChartItem = mapChartItem;
})();

/**
 * 默认投影器。
 */
(function(){
	var defaultProjector = function()
	{
		this._scale = 1;
		this._offsetX = 0;
	}

	// 经纬度转XY坐标。
	defaultProjector.prototype.lngLatToXY = function(lng, lat)
	{
		var p = {x: lng, y: -lat};

		// 修正位置，使中国地图位于屏幕中央。
		p.x += this._offsetX;
		if (p.x < -180) p.x += 360;

		p.x *= this._scale;
		p.y *= this._scale * 1.3;

		return p;
	}
	defaultProjector.prototype.XYToLngLat = function(x, y)
	{
		return undefined;
	}

	WbstChart.DefaultProjector = defaultProjector;
})();

/**
 * 默认样式协调器。
 */
(function(){
	var defaultStyleCoordinator = function()
	{

	}

	defaultStyleCoordinator.prototype.styleShape = function(g, level, info, type)
	{
		if (type == 'mouseout')
		{
			g.beginFill(0x005296).lineStyle(1, 0x16a2b5);
			// g.fillAlpha = 0.5;
		}
		else if (type == 'mouseover')
		{
			g.beginFill(0x1fe5fc).lineStyle(1, 0x16a2b5);
		}
	}

	WbstChart.DefaultStyleCoordinator = defaultStyleCoordinator;
})();